package com.yantong.controller.mall;

import com.yantong.service.CategoryService;
import com.yantong.annotation.Log;
import com.yantong.controller.BaseController;
import com.yantong.result.ResultVo;
import com.yantong.utils.PageUtils;
import com.yantong.pojo.Advert;
import com.yantong.pojo.vo.AdvertVos;
import com.yantong.service.AdvertService;
import com.yantong.service.BaTypeService;
import com.yantong.service.ConfigService;
import com.yantong.pojo.ProductCentre;
import com.yantong.service.ProductCentreService;
import com.yantong.service.ReservationBrandCategoryService;
import com.yantong.utils.ValidateUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广告控制类
 *
 * @author kanghaixin
 * @date 2018/8/29.11:22
 */
@Controller
@RequestMapping("/mall/advert")
public class AdvertController extends BaseController {
	private static final String prefix = "mall/advert";

	@Autowired
	private BaTypeService baTypeService;
	@Autowired
	private AdvertService advertService;
	@Autowired
	private ConfigService configService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ProductCentreService productCentreService;
	@Autowired
	private ReservationBrandCategoryService reservationBrandCategoryService;


	/**
	 * 广告列表页面
	 *
	 * @param model
	 * @return
	 */
	@RequiresPermissions("mall:advert:advert")
	@GetMapping()
	public String adverts(Model model) {
		model.addAttribute("baTypes", baTypeService.listBaTypes());
		model.addAttribute("imgPrefix", configService.getImgPrefix());
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/adverts";
	}

	/**
	 * 广告列表数据
	 *
	 * @param baTypeId
	 * @param advname
	 * @param offset
	 * @param limit
	 * @return
	 */
	@GetMapping("/list")
	@RequiresPermissions("mall:advert:advert")
	@ResponseBody
	public PageUtils<Advert> listAdverts(Integer baTypeId, String advname, Long centreId, int offset, int limit) {
		if (centreId == null) {
			centreId = getUserCentreId();
		}
		return advertService.listAdverts(baTypeId, advname, centreId,getUserTeamId(), offset, limit);
	}

	/**
	 * 不显示操作
	 *
	 * @param advertId
	 * @return
	 */
	@RequiresPermissions("mall:advert:showControl")
	@ResponseBody
	@PostMapping("/disableShow")
	public ResultVo disableShow(Long advertId) {
		if (advertId == null) {
			return ResultVo.error();
		}
		if (advertService.disableShow(advertId) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 显示操作
	 *
	 * @param advertId
	 * @return
	 */
	@RequiresPermissions("mall:advert:showControl")
	@ResponseBody
	@PostMapping("/enableShow")
	public ResultVo enableShow(Long advertId) {
		if (advertId == null) {
			return ResultVo.error();
		}
		if (advertService.enableShow(advertId) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 删除广告
	 *
	 * @param advertId
	 * @return
	 */
	@Log(module = "广告管理", operation = "删除广告")
	@RequiresPermissions("mall:advert:remove")
	@PostMapping("/remove")
	@ResponseBody
	public ResultVo remove(Long advertId) {
		if (advertId == null) {
			return ResultVo.error();
		}
		if (advertService.removeAdvert(advertId) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 批量删除广告
	 *
	 * @param ids
	 * @return
	 */
	@Log(module = "广告管理", operation = "批量删除广告")
	@ResponseBody
	@PostMapping("/batchRemove")
	@RequiresPermissions("mall:advert:batchRemove")
	public ResultVo batchRemove(@RequestParam("ids[]") Long[] ids) {
		if (ids.length < 1) {
			return ResultVo.error();
		}
		int result = advertService.batchRemove(Arrays.asList(ids));
		if (result < 0) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}


	/**
	 * 广告添加页面
	 *
	 * @param model
	 * @return
	 */
	@RequiresPermissions("mall:advert:add")
	@GetMapping("/add")
	public String add(Model model) {
		model.addAttribute("baTypes", baTypeService.listBaTypes());
		model.addAllAttributes(getCentreIdModelInfo());
		model.addAttribute("productLinkPrefix", "https://o.rjkj7.com/wemall/items/detail/");
		// model.addAttribute("categoryLinkPrefix", "https://o.rjkj7.com/wemall/items/list?");
		model.addAttribute("categoryLinkPrefix", "/pages/classify/classify?");
		model.addAttribute("categoryList", categoryService.listCategorys(0L));
		Map<String,Object> map = new HashMap<>();
		map.put("centreId",getUserCentreId());
        model.addAttribute("reservationBrandCategoryList", reservationBrandCategoryService.listByAll(map));
		return prefix + "/add";
	}

	/**
	 * 广告数据保存
	 *
	 * @return
	 */
	@Log(module = "广告管理", operation = "广告数据保存")
	@ResponseBody
	@RequiresPermissions("mall:advert:add")
	@PostMapping("/save")
	public ResultVo save(AdvertVos advertVo) {
		if (advertVo == null) {
			return ResultVo.error();
		}
		if(ValidateUtil.isEmptyString(advertVo.getTeamId())){
			advertVo.setTeamId(getUserTeamId()+"");
		}
		if (advertVo.getProductId() == null || advertVo.getProductId().equals("")) {
			if (advertVo.getLink().contains("&amp;")) {
				advertVo.setLink(advertVo.getLink().replace("&amp;", "&"));
			}
			if (advertService.addAdvert(advertVo) < 1) {
				return ResultVo.error();
			}
		} else {
			//截取商品Id
			String[] productId = advertVo.getProductId().split(",");
			for (int i = 0; i < productId.length; i++) {
				if (!productId[i].equals("") && productId[i] != null) {
					//得到商品
					ProductCentre pc = productCentreService.getProductCentre(Long.valueOf(productId[i]));
					if (pc == null) {
						return ResultVo.error();
					}
					advertVo.setLink("https://o.rjkj7.com/wemall/items/detail/".concat(productId[i]));
					advertVo.setCentreId(pc.getCentreId().toString());
					if (advertService.addAdvert(advertVo) < 1) {
						return ResultVo.error();
					}
				}
			}
		}
		return ResultVo.ok();
	}
  /*  public ResultVo save(Advert advert) {
        if (advert == null) {
            return ResultVo.error();
        }
        if (advertService.saveAdvert(advert)< 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }*/

	/**
	 * 广告编辑
	 * TODO: 待分类和商品接口开发完成
	 *
	 * @return
	 */
	@RequiresPermissions("mall:advert:edit")
	@GetMapping("/edit/{advertId}")
	public String edit(@PathVariable Long advertId, Model model) {
		model.addAttribute("baTypes", baTypeService.listBaTypes());
		model.addAttribute("advert", advertService.getByKey(advertId));
		model.addAttribute("categoryList", categoryService.listCategorys(0L));
		model.addAllAttributes(getCentreIdModelInfo());

		model.addAttribute("productLinkPrefix", "https://o.rjkj7.com/wemall/items/detail/");
		//model.addAttribute("categoryLinkPrefix", "https://o.rjkj7.com/wemall/items/list?");
		model.addAttribute("categoryLinkPrefix", "/pages/classify/classify?");
		Map<String,Object> map = new HashMap<>();
		map.put("centreId",getUserCentreId());
		model.addAttribute("reservationBrandCategoryList", reservationBrandCategoryService.listByAll(map));
		return prefix + "/edit";
	}

	/**
	 * 广告编辑
	 *
	 * @param advert
	 * @return
	 */
	@Log(module = "广告管理", operation = "广告编辑")
	@ResponseBody
	@RequiresPermissions("mall:advert:edit")
	@PostMapping("/update")
	public ResultVo update(Advert advert) {
		if (advert == null || advert.getId() == null) {
			return ResultVo.error();
		}
		if (advert.getLink().contains("&amp;")) {
			advert.setLink(advert.getLink().replace("&amp;", "&"));
		}
		if (advertService.updateAdvert(advert) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 链接到商品
	 *
	 * @param centreId
	 * @return
	 */
	@GetMapping("/linkToProduct")
	public String linkToProduct(String centreId, Model model) {
		model.addAttribute("centreId", centreId);
		model.addAttribute("imgPrefix", configService.getImgPrefix());
		return prefix + "/linkToProduct";
	}

	/**
	 * 可链接的商品列表
	 *
	 * @param centreId
	 * @param queryItem
	 * @param offset
	 * @param limit
	 * @return
	 */
	@ResponseBody
	@GetMapping("/linkProducts")
	public PageUtils<ProductCentre> listLimitProducts(String centreId, String queryItem, int offset, int limit) {
		List<String> centreIds = null;
		if (!centreId.equals("")) {
			centreIds = Arrays.asList(centreId.split(","));
		}
		return productCentreService.listByTitleAndCentreId(null, queryItem, centreIds, offset, limit);
	}
    /*@ResponseBody
    @GetMapping("/linkProducts")
    public PageUtils<ProductCentre> listLimitProducts(Long centreId,String queryItem, int offset, int limit) {
        return productCentreService.listByTitleAndId(null, queryItem, centreId,offset, limit);
    }*/
}
